<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.bootcss.com/jquery/3.5.0/jquery.js"></script>
    <style>
      .box img {
        height: 200px;
        width: 200px;
      }
    </style>
  </head>
  <body>
    <form onsubmit="return false">
      <div class="box">
        <img src="/img/add.png" alt="" />
        <input type="file" name="file" id="file" accept="image/*" hidden />
      </div>
      <div>
        <button class="add">添加</button>
        <button class="upload">上传</button>
      </div>
    </form>
  </body>

  <script src="./layer/layer.js"></script>
  <script>
    let img = null;
    // 点击添加
    $(".add").click(function () {
      $(".box").append(`<img src="/img/add.png" alt="" />`);
    });

    // 点击图片框
    $(".box").on("click", "img", function () {
      img = this;
      // $(this).next().click();
      $(".box input[type=file]").click();
      
    });

    let file = [];
    $("#file").change(function () {
      file.push(this.files[0]);
      img.src = URL.createObjectURL(this.files[0]);
    });

    $(".upload").click(function () {
      if (file.length < 1) {
        return alert("请选择图片");
      }
      let fileData = new FormData();
      file.forEach((element) => {
        fileData.append("multiFile", element);
      });
      $.ajax({
        url: "/upload",
        data: fileData,
        method: "post",
        processData: false,
        contentType: false,
        success(data) {
          layer.msg(data.data);
          location.href = "index.html";
        },
      });
    });
  </script>
</html>
